package tom.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.Timer;

public class IdlePopup extends PopupPanel {
	public static IdlePopup popup = GWT.create(IdlePopup.class);

	private Timer countdown = new Timer() {
		@Override
		public void run() {
			if (popup.isAttached()) {
				popup.hide();
				FormLogin.frmLogin.logout();
			}
		}
	};
	private Label label;

	public IdlePopup() {
		this.setPixelSize(190, 100);
		this.setAnimationEnabled(true);
		this.setAutoHideEnabled(true);

		this.addAttachHandler(new AttachEvent.Handler() {

			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if (event.isAttached()) {
					countdown.schedule(10000); // keep warning time to 3 minute   = 3*60000
				} else
					countdown.cancel();
			}
		});
		this.addCloseHandler(new CloseHandler<PopupPanel>() {

			@Override
			public void onClose(CloseEvent<PopupPanel> event) {
				Library.getService().getSessVar("user",
						new AsyncCallback<String>() {
							@Override
							public void onSuccess(String result) {
							}

							@Override
							public void onFailure(Throwable caught) {
								Window.Location.reload();
							}
						});
			}
		});
		label = new Label("คลิกเมาส์ เพิ่อรักษา การติดต่อ กับเซิฟเวอร์");
		label.setStyleName("popup");
		// label.setHorizontalAlignment(Label.ALIGN_CENTER);
		this.setWidget(label);
		label.addMouseMoveHandler(new MouseMoveHandler() {
			@Override
			public void onMouseMove(MouseMoveEvent event) {
				IdlePopup.this.hide();
			}
		});
	}
}
